# -*- coding: utf-8 -*-
# Author: xiantingDeng
# File: read_util.py
# Time: 11:28

import configparser
import os

import yaml

from common.util.file_util import get_data_file_path

class OperationIni():
    def __init__(self, filename):
        self.file_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))),
                                      "config", filename)

    def get_ini_file_data(self):
        '''
        读取ini配置文件所有节点信息
        :param file_path: ini配置文件下的绝对路径
        :return: 返回ini文件中所有节点信息，当文件不存在或没有数据时返回空字典：{}
        '''
        config = configparser.ConfigParser()
        config.read(self.file_path)
        dict_data = dict()
        for item in config.items():
            temp_dict = dict()
            if item[0] == "DEFAULT":
                continue
            line = config.items(item[0])
            temp_dict[item[0]] = dict(line)
            dict_data.update(temp_dict)
        return dict_data

    def get_ini_file_path_section_data(self, section_name):
        '''
        读取ini配置文件指定节点信息
        :param section_name:节点名称
        :return:返回ini文件中指定节点信息，当文件不存在或没有数据时返回空字典：{}
        '''
        config = configparser.ConfigParser()
        config.read(self.file_path)
        dict_data = {}
        if config.has_section(section_name):
            options = config.options(section_name)
            for option in options:
                kv_dict = {}
                item = config.get(section_name, option)
                kv_dict[option] = item
                dict_data.update(kv_dict)
            return dict_data
        else:
            return {}

    def get_ini_option_data(self, section_name, option_name):
        '''
        获取配置文件下制定节点下制定键的值
        :param file_path:ini配置文件绝对路径
        :param section_name:节点名称
        :param option_name:节点下键值
        :return:返回指定节点下指定键的值，当文件不存在或节点或键不存在时返回None
        '''
        config = configparser.ConfigParser()
        config.read(self.file_path)
        if config.has_section(section_name):
            if config.has_option(section_name, option_name):
                value = config.get(section_name, option_name)
                return value
        else:
            return None


class OperationYaml():
    def __init__(self, filename):
        self.file_path = get_data_file_path(filename)

    def get_yaml_data(self):
        '''
        获取yaml文件数据
        :return:  以字典方式返回
        '''
        with open(self.file_path, "r",encoding="utf-8") as fp:
            file_conten = fp.read()
        conten = yaml.load(file_conten, yaml.FullLoader)
        return conten




if __name__ == '__main__':
    print(OperationIni("usr.ini").get_ini_file_path_section_data("Identification"))
    # pass